package download;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.AtomicLong;

class DownloadFile {

    private final RandomAccessFile file;
    private final FileOutputStream fos;
    // 已写入的长度
    private final AtomicLong wroteSize;
    private final Logger logger;

    DownloadFile(String fileName, long fileSize, Logger logger) throws IOException {
        this.wroteSize = new AtomicLong(0);
        this.logger = logger;
        file = new RandomAccessFile(fileName, "rw");
        file.setLength(fileSize);
        fos = new FileOutputStream(file.getFD());
    }

    /**
     * 写数据
     * @param offset 写偏移量
     * @param buffer 数据
     * @throws IOException 写数据出现异常
     */
    void write(byte[] buffer, int len, long offset, int threadId, long upperBound) throws IOException {
        synchronized (this) {
            file.seek(offset);
            fos.write(buffer, 0, len);
        }
        wroteSize.addAndGet(len);
        logger.updateLog(threadId, len, offset + len, upperBound);
    }

    /**
     * @return 已经下载的数据量，为了知道何时结束整个任务，以及统计信息
     */
    long getWroteSize() {
        return wroteSize.get();
    }

    // 继续下载时调用
    void setWroteSize(long wroteSize) {
        this.wroteSize.set(wroteSize);
    }

    void close() {
        try {
            file.close();
        } catch (IOException ignore) {}
    }
}
